__author__ = 'Omri'

import datetime
import webapp2
from Model import *


class NewUserHandler(webapp2.RequestHandler):
    def get(self):
        email = self.request.get("email")
        user = User(Email = email,
                    Password = "12345",
                    Name = None,
                    Gender = "Male",
                    Country = "Israel",
					Grade = 0,
                    Birthdate=datetime.date(1980, 1, 1),
                    TotalDistance = float(0))
        user.put()
        self.response.content_type = 'application/json'
        self.response.out.write(json.dumps({"user" : user.key.id()}))

class SignInHandler(webapp2.RequestHandler):
    def get(self):
        email = self.request.get("email")
        name = None
        birthday = self.request.get("birthday")
        user = User.query(User.Email == email).get()
        if not user: #id the user doesn't exist - signUp
            user = User(Email = email,
                    Password = "12345",
                    Gender = "Male",
                    Country = "Israel",
					Grade = 0,
                    Birthdate=datetime.date(1980, 1, 1),
                    TotalDistance = float(0))
            user.put()
        else:
            name = user.Name
        nickname = user.Name
        self.response.content_type = 'application/json'
        self.response.out.write(json.dumps({"success" : "success", "userId" : user.key.id(), "hasName": "true" if name else "false", "nickname":nickname}))

class AchievementsHandler(webapp2.RequestHandler):
    def post(self):
        userId = int(self.request.POST.get('userId'))
        user_key = ndb.Key('User', userId)
        user = user_key.get()

        self.response.out.write(json.dumps({"score" : user.Grade, "totalDistance" : user.TotalDistance,\
                                            "lastRun" : str(user.LastRun) if user.LastRun else "N/A",\
                                            "bestPlace" : user.BestPlace if user.BestPlace else "",\
                                            "absolutePosition" : user.getAbsolutePosition, "averageSpeed":user.AverageSpeed}))

class NicknameHandler(webapp2.RequestHandler):
    def post(self):
        nickname = self.request.POST.get('nickname')
        logging.debug("looking for nickname: %s", nickname)
        user = User.query(User.Name == nickname).get()
        if user:
            logging.debug("Found user with that nickname")
            success = False
        else:
            userId = int(self.request.POST.get('userId'))
            user = ndb.Key('User', userId).get()
            user.Name = nickname
            user.put()
            success = True
        logging.debug("Nickname updated successfully" if success else "Failed to update nickname")
        self.response.content_type = 'application/json'
        self.response.out.write(json.dumps({"success": "success" if success else "failed"}))

